<?php

use App\Kit\RedisKey;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;

/**
 * 检查数字范围有没有重合
 * 参数示例: [ [1,3], [2,4], [5,7] ]
 */
function find_overlap($ranges) {
    //去掉不正确的项
    foreach($ranges as $k => $range){
        if(!isset($range[0]) || !isset($range[1])){
            unset($ranges[$k]);
        }
    }
    $ranges = array_values($ranges);

    // 按照范围的起始位置进行排序
    usort($ranges, function($a, $b) {
        return $a[0] - $b[0];
    });

    // 遍历范围，检查重合
    for ($i = 0; $i < count($ranges) - 1; $i++) {

        $current = $ranges[$i];
        $next = $ranges[$i + 1];

        // 如果当前范围的结束位置大于等于下一个范围的起始位置，则存在重合
        if ($current[1] >= $next[0]) {
            return [$current, $next];
        }
    }

    // 没有找到重合的范围
    return null;
}

/**
 * 文件中查找字符串
 */

 function find_string($file, $search) {

    //文件不存在直接返回falst
    if(!file_exists($file) ) {
        return false;
    }

    $handle = fopen($file, "r");
    if ($handle) {
        // 定义每次读取的块大小
        $chunkSize = 8192; // 8KB
        $buffer = '';

        while (!feof($handle)) {
            // 读取文件的一部分
            $buffer .= fread($handle, $chunkSize);
            // 检查是否在当前缓冲区中找到了目标字符串
            if (strpos($buffer, $search) !== false) {
                fclose($handle);
                return true; // 找到目标字符串，返回 true
            }
            // 为防止缓冲区无限增长，保留最后一段以应对跨块搜索情况
            if (strlen($buffer) > strlen($search)) {
                $buffer = substr($buffer, -strlen($search));
            }
        }
        fclose($handle);
    }
    return false; // 如果遍历完整个文件仍未找到，返回 false
}

//语言, 传入中文
function _t($cn) {
    $lang = App::make('language');
    if($lang == 'en') {
        $translate_file = base_path('lang/cn.php');
        if(file_exists($translate_file)) {
            $langs = include_once($translate_file);
            if(is_array($langs)) {
                return $langs[$cn] ?? $cn;
            }
        }
    }
    return $cn;
}


function generate_secret($length = 40) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

//获取订单号
use Illuminate\Support\Facades\Redis;
function get_order_sn() {
    $key = RedisKey::order_sn();
    $incr = Redis::incr($key);

    if(strlen($incr) < 2) {
        $pad = str_repeat('0', 2 - strlen($incr));
        $incr = $pad . $incr;
    }
    $sn = $incr;

    $ttl = Redis::ttl($key);
    if($ttl == -1) {
        Redis::expire($key, 86400);
    }

    return $sn;
}

//大客户入仓单号
function get_big_order_sn($number = 5) {
    $key = RedisKey::order_sn();
    $incr = Redis::incr($key);

    if(strlen($incr) < $number) {
        $pad = str_repeat('0', $number - strlen($incr));
        $incr = $pad . $incr;
    }
    $sn = $incr;

    $ttl = Redis::ttl($key);
    if($ttl == -1) {
        Redis::expire($key, 86400);
    }

    return $sn;
}

//获取批次号
function get_batch_sn() {
    $key = RedisKey::batch_sn();
    $incr = Redis::incr($key);

    $prefix_incr = intval($incr / 9999)  % 25;
    $incr = $incr % 9999;

    $sn = chr(ord('A') + $prefix_incr);

    if(strlen($incr) < 4) {
        $pad = str_repeat('0', 4 - strlen($incr));
        $incr = $pad . $incr;
    }
    $sn .= $incr;

    return $sn;
}

function calculateTotalScore($first, $second) {
    // 定义权重百分比
    $weight1 = 0.5;
    $weight2 = 0.5;

    // 计算各部分得分
    $score1 = $first * $weight1;
    $score2 = $second * $weight2;

    // 计算总分并确保不超过 100
    $totalScore = min(100, $score1 + $score2);

    return $totalScore;
}

//读取ip的时区等信息
use GeoIp2\Database\Reader;

function get_ip_info($ip) {
    $db_file = public_path('GeoLite2-City.mmdb');
    $reader = new Reader($db_file);
    $record = $reader->city($ip);
    return $record;
}

//获取时区和GMT的时差
function gmt_time_diff($timezoneString) {
    // 创建两个时区对象，一个是传入的时区，另一个是GMT
    $targetTimeZone = new DateTimeZone($timezoneString);
    $gmtTimeZone = new DateTimeZone('GMT');

    // 创建当前时间的DateTime对象，并设置为GMT时区
    $currentDateTime = new DateTime('now', $gmtTimeZone);

    // 计算目标时区的UTC偏移量
    $targetOffset = $targetTimeZone->getOffset($currentDateTime);

    // 将UTC偏移量转换为小时
    $hoursDifference = $targetOffset / 3600;

    // 返回时差，如果是负数，表示目标时区在GMT的西边
    if($hoursDifference > 0) {
        $hoursDifference = '+'.$hoursDifference;
    }
    return $hoursDifference;
}

//GMT时间转其他时区
function gmt_convert_time(string $time, $targetTimeZone) {
    $dateTime = new DateTime($time, new DateTimeZone('GMT'));
    
    // 创建目标时区对象
    $targetDateTimeZone = new DateTimeZone($targetTimeZone);
    
    // 将时间从UTC转换到目标时区
    $dateTime->setTimezone($targetDateTimeZone);
    
    // 返回转换后的时间
    return $dateTime->format('Y-m-d H:i:s');
}

//其他时区转GMT时间
function convert_time_to_gmt(string $time, $otherTimeZone){
    $dateTime = new DateTime($time, new DateTimeZone($otherTimeZone));
    
    // 创建目标时区对象
    $targetDateTimeZone = new DateTimeZone('GMT');
    
    // 将时间从UTC转换到目标时区
    $dateTime->setTimezone($targetDateTimeZone);
    
    // 返回转换后的时间
    return $dateTime->format('Y-m-d H:i:s');
}

//获取指定时区的当天对应的GMT开始结束时间
function get_time_zone_today($time_zone) {
    $timezone = new DateTimeZone($time_zone);
    $now = new DateTime('now', $timezone);
    $now->setTime(0, 0, 0);
    $start = $now->format('Y-m-d H:i:s');

    $end = $now->modify('+1 day')->format('Y-m-d H:i:s');

    return [$start, $end];
}

function getCode($key, $prefix = '', $num = 4)
{
    $code = Cache::store('file')->get($key);
    if($code) {
        $code++;
    }else{
        $code = 1;
    }
    Cache::store('file')->set($key, $code);
    return $prefix . (string)sprintf("%0" . $num . "d", $code);
}

function get_templateId($phone)
{
    // 去除可能的空格和特殊字符
    $phone = preg_replace('/\D/', '', $phone);

    // 判断手机号前缀
    if (strpos($phone, '861') === 0) {
        $templateId = config('sms.templateId');
    } elseif (strpos($phone, '852') === 0 || strpos($phone, '853') === 0) {
        $templateId = config('sms.templateId_HK');
    }  else {
        $templateId = config('sms.templateId');
    }
    return $templateId;
}


function hexHash($message) {
    return bin2hex(hash('sha256', $message, true));
}